﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace kwt.core
{
    /// <summary>
    /// IO处理辅助类
    /// </summary>
    public class IOHelper
    {

        /// <summary>
        /// 获取所有引用某个样式文件的非import文件列表
        /// </summary>
        /// <param name="path">要查询的被引用样式文件完整路径</param>
        /// <returns>所有引用了该文件的文件完整路径列表</returns>
        public static List<CssResult> ParentFiles(string[] paths)
        {
            List<CssResult> results = new List<CssResult>();
            foreach (string path in paths)
            {
                string Dir = Path.GetDirectoryName(path);
                string[] files = Directory.GetFiles(Dir, "*.css", SearchOption.AllDirectories);
                List<string> parentFiles = new List<string>();
                results.Add(ParentFiles(path, files));
            }
            return results;
        }

        public static List<CssResult> ChildFiles(string[] paths)
        {
            List<CssResult> results = new List<CssResult>();
            foreach (string path in paths)
            {

                string Dir = Path.GetDirectoryName(path);
                if (!Dir.EndsWith("\\"))
                    Dir += "\\";
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string content = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                fs.Close();
                fs.Dispose();
                content = RemoveComment(content);
                string pattern = "@import\\s+url\\(\\W?(?<result>[a-zA-Z0-9-_\\.]+)\\W?\\)";
                Regex rex = new Regex(pattern, RegexOptions.IgnoreCase);
                List<string> childFiles = new List<string>();
                List<string> fullPathFiles = new List<string>();
                foreach (Match m in rex.Matches(content))
                {
                    string tempPath = m.Groups["result"].ToString();
                    if (string.IsNullOrEmpty(tempPath))
                        continue;
                    string file = Path.Combine(Dir, tempPath);
                    //string[] subChildFiles = ChildFiles(file);
                    //if (subChildFiles.Length > 0)
                    //{
                    //    childFiles.Add(tempPath + "[+]");
                    //    childFiles.AddRange(subChildFiles.AsEnumerable());
                    //}
                    //else
                    //{
                    childFiles.Add(tempPath.ToString());
                    fullPathFiles.Add(file);
                    //}
                }
                results.Add(new CssResult()
                {
                    RootFile = path,
                    RelativeFile = childFiles.ToArray(),
                    RelativeFileWithFullPath = fullPathFiles.ToArray()
                });
            }
            return results;
        }

        /// <summary>
        /// 获取所有引用某个样式文件的非import文件列表
        /// </summary>
        /// <param name="path">要查询的被引用样式文件完整路径</param>
        /// <param name="files">有可能引用该文件的所有样式文件完整路径</param>
        /// <returns>所有引用了该文件的文件完整路径列表</returns>
        public static CssResult ParentFiles(string path, string[] files)
        {
            List<string> parentFiles = new List<string>();
            List<string> fullPathFiles = new List<string>();
            foreach (string file in files)
            {
                if (file == path)
                    continue;
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string content = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                fs.Close();
                fs.Dispose();
                content = RemoveComment(content);
                string pattern = "url\\([\'|\"]?" + IOHelper.EvaluateRelativePath(file, path).Replace(@"../", @"\\.\./") + "[\'|\"]?\\)";
                if (Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase))
                {
                    //string[] grandFiles = ParentFiles(file, files);
                    //if (grandFiles.Length > 0)
                    //{
                        //parentFiles.Add(EvaluateRelativePath(path,file) + "[+]");
                        //parentFiles.AddRange(grandFiles.AsEnumerable());
                   //}
                    //else
                    //{
                    fullPathFiles.Add(file);
                    parentFiles.Add(EvaluateRelativePath(path, file));
                    //}
                }
            }

            return new CssResult()
            {
                RootFile = path,
                RelativeFile = parentFiles.ToArray(),
                RelativeFileWithFullPath = parentFiles.ToArray()
            };
        }

        /// <summary>
        /// 计算一个绝对路径相对于另一个绝对路径的相对路径
        /// </summary>
        /// <param name="mainDirPath">要计算的基础路径</param>
        /// <param name="absoluteFilePath">要计算的目标路径</param>
        /// <returns>相对路径</returns>
        public static string EvaluateRelativePath(string mainDirPath, string absoluteFilePath)
        {
            string[] firstPathParts = mainDirPath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);
            string[] secondPathParts = absoluteFilePath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar);

            int sameCounter = 0;
            for (int i = 0; i < Math.Min(firstPathParts.Length, secondPathParts.Length); i++)
            {
                if (!firstPathParts[i].ToLower().Equals(secondPathParts[i].ToLower()))
                {
                    break;
                }
                sameCounter++;
            }

            if (sameCounter == 0)
            {
                return absoluteFilePath;
            }

            string newPath = String.Empty;
            for (int i = sameCounter; i < firstPathParts.Length; i++)
            {
                if (i > sameCounter)
                {
                    newPath += "..";
                    newPath += Path.DirectorySeparatorChar;
                }

            }
            if (newPath.Length == 0)
            {
                newPath = "";
            }
            for (int i = sameCounter; i < secondPathParts.Length; i++)
            {
                if (i > sameCounter)
                {
                    newPath += Path.DirectorySeparatorChar;
                }
                newPath += secondPathParts[i];
            }
            return newPath.Replace("\\", "/");
        }

        public static string RemoveComment(string cssCode)
        {
            string patComment = @"/\*.[^/]*\*/";
            Regex rex = new Regex(patComment);
            return rex.Replace(cssCode, "");
        }
    }
}
